package com.ouc.entity;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @Name: Shape
 * @Description: 形状
 * @Author: Mr.Tong
 */
@Data
public abstract class Shape {
    //形状id
    private Integer id;
    //编码字段
    private String shapeCode;
    //类型
    private String shapeType;
    //产品周长
    private Double perimeter;
    //产品面积
    private Double area;

    public abstract Double perimeter();

    public abstract Double area();

    public abstract Integer unitAreaPrice();

    public Double getPerimeter() {
        if (perimeter == null) {
            perimeter = perimeter();
        }
        return perimeter;
    }

    public Double getArea() {
        if (area == null) {
            area = area();
        }
        return area;
    }

    //一个形状肯定有很多的产品
    private List<Frame> frames;


    /**
     * @Description: 反序列化-将json字符串转化成json对象
     * @Author: Mr.Tong
     */
    public static class ShapeDeserializer extends StdDeserializer<Shape> {
        protected ShapeDeserializer() {
            super(Shape.class);
        }

        @Override
        public Shape deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = jsonParser.getCodec().readTree(jsonParser);
            String type = node.get("shapeType").asText();
            if (type.equalsIgnoreCase("c")) {
                Shape shape = mapper.readValue(node.toString(), Circle.class);
                return shape;
            } else if (type.equalsIgnoreCase("r")) {
                Shape shape = mapper.readValue(node.toString(), Rectangle.class);
                return shape;
            } else if (type.equalsIgnoreCase("t")) {
                Shape shape = mapper.readValue(node.toString(), Triangle.class);
                return shape;
            }
            return mapper.readValue(node.toString(), Shape.class);
        }
    }
}
